package com.cloud.util.qrcode

import com.google.zxing.*
import com.google.zxing.client.j2se.BufferedImageLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import java.awt.BasicStroke
import java.awt.Color
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
import javax.imageio.ImageIO
import java.awt.RenderingHints
import java.awt.geom.RoundRectangle2D


/**
 * 二维码生成和读的工具类
 *
 */
object QrCodeCreateUtil {

    /**
     * 生成包含字符串信息的二维码图片
     * @param content 二维码携带信息
     * @param qrCodeSize 二维码图片大小
     * @param imageFormat 二维码的格式
     * @throws WriterException
     * @throws IOException
     */
    @Throws(WriterException::class, IOException::class)
    fun createQrCode(content: String, qrCodeSize: Int = 900): BufferedImage {
        //设置二维码纠错级别ＭＡＰ
        val hintMap = mapOf(EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.L) // 矫错级别
        //创建比特矩阵(位矩阵)的QR码编码的字符串
        val byteMatrix = QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap)
        // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
        val matrixWidth = byteMatrix.width
        val image = BufferedImage(matrixWidth - 200, matrixWidth - 200, BufferedImage.TYPE_INT_RGB)
        image.createGraphics()
        val graphics = image.graphics as Graphics2D
        graphics.color = Color.WHITE
        graphics.fillRect(0, 0, matrixWidth, matrixWidth)
        // 使用比特矩阵画并保存图像
        graphics.color = Color.BLACK
        for (i in 0 until matrixWidth) {
            for (j in 0 until matrixWidth) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i - 100, j - 100, 1, 1)
                }
            }
        }
        return image
    }

    @Throws(IOException::class)
    fun logoMatrix(matrixImage: BufferedImage, logo: BufferedImage): BufferedImage {
        /**
         * 读取二维码图片，并构建绘图对象
         */
        val g2 = matrixImage.createGraphics()

        val matrixWidth = matrixImage.width
        val matrixHeigh = matrixImage.height

        //开始绘制图片
        g2.drawImage(logo, matrixWidth / 5 * 2, matrixHeigh / 5 * 2, matrixWidth / 5, matrixHeigh / 5, null)//绘制
        val stroke = BasicStroke(5.toFloat(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)
        g2.stroke = stroke// 设置笔画对象
        //指定弧度的圆角矩形
        val round = RoundRectangle2D.Float(matrixWidth.toFloat() / 5 * 2, matrixHeigh.toFloat() / 5 * 2, matrixWidth.toFloat() / 5, matrixHeigh.toFloat() / 5, 20.toFloat(), 20.toFloat())
        g2.color = Color.white
        g2.draw(round)// 绘制圆弧矩形

        //设置logo 有一道灰色边框
        val stroke2 = BasicStroke(1.toFloat(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)
        g2.stroke = stroke2// 设置笔画对象
        val round2 = RoundRectangle2D.Float(matrixWidth.toFloat() / 5 * 2 + 2, matrixHeigh.toFloat() / 5 * 2 + 2, matrixWidth.toFloat() / 5 - 4, matrixHeigh.toFloat() / 5 - 4, 20.toFloat(), 20.toFloat())
        g2.color = Color(128, 128, 128)
        g2.draw(round2)// 绘制圆弧矩形*/
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)

        matrixImage.flush()
        g2.dispose()
        return matrixImage
    }

    /**
     * 读二维码并输出携带的信息
     */
    @Throws(IOException::class)
    fun readQrCode(inputStream: InputStream) :String{
        //从输入流中获取字符串信息
        val image = ImageIO.read(inputStream)
        //将图像转换为二进制位图源
        val source = BufferedImageLuminanceSource(image)
        val bitmap = BinaryBitmap(HybridBinarizer(source))
        val reader = QRCodeReader()
        var result: Result? = null
        try {
            result = reader.decode(bitmap)
        } catch (e: ReaderException) {
            e.printStackTrace()
        }

       return result!!.text
    }


    /**
     * 测试代码
     * @throws WriterException
     */
    @Throws(IOException::class, WriterException::class)
    @JvmStatic
    fun main(args: Array<String>) {
//        val image=createQrCode("https://blog.csdn.net/aqi00/article/details/74908622", 900)
//    ImageIO.write(image,"JPEG", File("/Users/imac/Documents/workspace/test.jpg"))

        //QiniuCloudUtil().put64image(QiniuCloudUtil().getBytes(image)!!,UUID.randomUUID().toString())
        readQrCode(FileInputStream(File("/Users/imac/Library/Containers/com.tencent.xinWeChat/Data/Library/Caches/com.tencent.xinWeChat/2.0b4.0.9/3c1f0da59b2328438da9dcb2659bf0eb/dragImgTmp/WeChat1c11fa9faba586d65f9d0d9f4862cba1.png")))
    }

}